import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'dart:io' show Platform;
import '../services/audio_player_service.dart';
import '../models/song.dart';
import 'lyrics_view.dart';
import 'package:flutter/services.dart';

class PlayerSidebar extends StatefulWidget {
  final Song? currentSong;
  final AudioPlayerService audioPlayerService;

  const PlayerSidebar({
    super.key,
    required this.currentSong,
    required this.audioPlayerService,
  });

  @override
  State<PlayerSidebar> createState() => _PlayerSidebarState();
}

class _PlayerSidebarState extends State<PlayerSidebar> {
  bool _showVolumeSlider = false;
  final LayerLink _layerLink = LayerLink();
  OverlayEntry? _overlayEntry;
  OverlayEntry? _backdropEntry;
  bool isMute = false;
  double _volume = 1.0;
  static const platform = MethodChannel('com.example.myapp/volume');

  @override
  void initState() {
    super.initState();
    _initVolumeControl();
  }


  @override
  void didUpdateWidget(PlayerSidebar oldWidget) {
    super.didUpdateWidget(oldWidget);
    print("play side didUpdateWidget ${oldWidget.currentSong?.artist}  ${oldWidget.currentSong?.localPath}");
    if (oldWidget.currentSong?.localPath != widget.currentSong?.localPath && widget.currentSong != null) {
        widget.audioPlayerService.playSong(widget.currentSong as Song);
    }
  }

  void _initVolumeControl() async {
    if (Platform.isMacOS) {
      try {
        final double volume = await platform.invokeMethod('getSystemVolume');
        setState(() {
          _volume = volume;
        });
      } on PlatformException catch (e) {
        print("Failed to get volume: '${e.message}'.");
      }

      // 初始化时获取系统音量
      // final volume = await WindowUtils.getSystemVolume();
      // widget.audioPlayer.setVolume(volume);

      // // 监听系统音量变化
      // WindowUtils.onSystemVolumeChanged.listen((volume) {
      //   widget.audioPlayer.setVolume(volume);
      //   if (mounted) {
      //     setState(() {
      //       isMute = volume <= 0;
      //     });
      //   }
      // });
    }
  }

  void _hideVolumeControl() {
    _overlayEntry?.remove();
    _overlayEntry = null;
    _backdropEntry?.remove();
    _backdropEntry = null;
    if (mounted) {
      setState(() => _showVolumeSlider = false);
    }
  }

  void _showVolumeControl() {

  print("show volumsss: ${_showVolumeSlider}");
    if (_showVolumeSlider) return;

    setState(() => _showVolumeSlider = true);
    _backdropEntry = OverlayEntry(
      builder: (context) => Positioned.fill(
        child: GestureDetector(
          onTap: _hideVolumeControl,
          behavior: HitTestBehavior.translucent,
          child: Container(color: Colors.transparent),
        ),
      ),
    );

    _overlayEntry = OverlayEntry(
      builder: (context) => Positioned(
        height: 230,
        width: 45,
        child: CompositedTransformFollower(
          link: _layerLink,
          targetAnchor: Alignment.topRight,
          followerAnchor: Alignment.bottomRight,
          offset: const Offset(0, -5),
          child: Material(
            color: Colors.white,
            elevation: 4,
            borderRadius: BorderRadius.circular(4),
            child: Padding(
              padding: const EdgeInsets.symmetric(vertical: 2, horizontal: 4),
              child: SizedBox(
                height: 120,
                width: 32,
                child: StreamBuilder<double>(
                  stream: widget.audioPlayerService.volumeStream,
                  builder: (context, snapshot) {
                    isMute = _volume <= 0;
                    return Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        // Icon(
                        //   volume == 0
                        //     ? Icons.volume_off
                        //     : volume < 0.5
                        //       ? Icons.volume_down
                        //       : Icons.volume_up,
                        //   size: 14,
                        // ),
                        // const SizedBox(height: 4),
                        Expanded(
                          child: _buildVolumeSlider(_volume),
                        ),
                      ],
                    );
                  },
                ),
              ),
            ),
          ),
        ),
      ),
    );

    final overlay = Overlay.of(context);
    overlay.insert(_backdropEntry!);
    overlay.insert(_overlayEntry!);
  }

  Widget _buildVolumeSlider(double volume) {
    return RotatedBox(
      quarterTurns: -1,
      child: SliderTheme(
        data: const SliderThemeData(
          trackHeight: 2,
          thumbShape: RoundSliderThumbShape(
            enabledThumbRadius: 6,
          ),
        ),
        child: Slider(
          value: volume,
          min: 0.0,
          max: 1.0,
          onChanged: (value) {
            widget.audioPlayerService.setVolume(value);
            // if (Platform.isMacOS) {
            //   WindowUtils.setSystemVolume(value);
            // }
            setState(() {
              _volume = value;
            });
          },
        ),
      ),
    );
  }

  @override
  void dispose() {
    _hideVolumeControl();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 300,
      color: Colors.grey[100],
      child: Column(
        children: [
          // 歌曲信息
          Container(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                Text(
                  widget.currentSong?.title ?? '未选择歌曲',
                  style: const TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 8),
                Text(widget.currentSong?.artist ?? ''),
              ],
            ),
          ),

          // 歌词显示
          Expanded(
            child: widget.currentSong?.lyrics != null
                ? StreamBuilder<Duration>(
                    stream: widget.audioPlayerService.positionStream,
                    builder: (context, snapshot) {
                      final position = snapshot.data ?? Duration.zero;
                      return StreamBuilder<Duration?>(
                        stream: widget.audioPlayerService.durationStream,
                        builder: (context, snapshot) {
                          final duration = snapshot.data ?? Duration.zero;
                          return LyricsView(
                            lyrics: widget.currentSong!.lyrics!,
                            position: position,
                            duration: duration,
                          );
                        },
                      );
                    },
                  )
                : const Center(child: Text('暂无歌词')),
          ),

          // 播放控制器
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              IconButton(
                icon: const Icon(Icons.skip_previous),
                onPressed: widget.currentSong != null
                    ? () => widget.audioPlayerService.playPrevious()
                    : null,
              ),
              StreamBuilder<PlayerState>(
                stream: widget.audioPlayerService.playingStream,
                builder: (context, snapshot) {
                  return IconButton(
                    icon: Icon(snapshot.data == PlayerState.playing ? Icons.pause : Icons.play_arrow),
                    onPressed: widget.currentSong != null
                        ? () => widget.audioPlayerService.togglePlay()
                        : null,
                  );
                },
              ),
              IconButton(
                icon: const Icon(Icons.skip_next),
                onPressed: widget.currentSong != null
                    ? () => widget.audioPlayerService.playNext()
                    : null,
              ),
            ],
          ),

          // 进度条和音量控制
          Row(
            children: [
              // 进度条部分
              Expanded(
                child: StreamBuilder<Duration>(
                  stream: widget.audioPlayerService.positionStream,
                  builder: (context, snapshot) {
                    final position = snapshot.data ?? Duration.zero;
                    return StreamBuilder<Duration?>(
                      stream: widget.audioPlayerService.durationStream,
                      builder: (context, snapshot) {
                        final duration = snapshot.data ?? Duration.zero;
                        return Column(
                          children: [
                            Slider(
                              value: position.inMilliseconds.toDouble(),
                              max: duration.inMilliseconds.toDouble(),
                              onChanged: (value) {
                                widget.audioPlayerService.seek(
                                    Duration(milliseconds: value.toInt()));
                              },
                            ),
                            Padding(
                              padding:
                                  const EdgeInsets.symmetric(horizontal: 16),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(_formatDuration(position)),
                                  Text(_formatDuration(duration)),
                                ],
                              ),
                            ),
                          ],
                        );
                      },
                    );
                  },
                ),
              ),
              // 音量控制图标
              CompositedTransformTarget(
                link: _layerLink,
                child: IconButton(
                  icon: Icon(isMute ? Icons.volume_off : Icons.volume_up,
                      size: 20),
                  onPressed: _showVolumeControl,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final minutes = twoDigits(duration.inMinutes.remainder(60));
    final seconds = twoDigits(duration.inSeconds.remainder(60));
    return '$minutes:$seconds';
  }
}
